package com.kgc.dao.impl;

import com.kgc.dao.BranchesDao;
import com.kgc.entity.Branches;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BranchesDaoImpl extends BaseDao implements BranchesDao {
    @Override
    public List<Branches> listBranches() {
        List<Branches> list = new ArrayList<Branches>();
        String sql = "select * from branches";
        rs = this.getResultSet(sql,null);
        try {
            while (rs.next()){
                Branches b = new Branches();
                b.setId(rs.getInt("id"));
                b.setAddress(rs.getString("address"));
                b.setBusinessno(rs.getString("businessno"));
                b.setCityarea(rs.getString("cityarea"));
                b.setName(rs.getString("name"));
                b.setSummary(rs.getString("summary"));
                b.setTelephone(rs.getString("telephone"));
                list.add(b);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.closeAll();
        }


        return list;
    }

    @Override
    public int countBranchesByBusinessNo(String no) {
        int count = 0;
        String sql = "select count(*) from branches where businessno = ?";
        rs = this.getResultSet(sql,new Object[]{no});
        try {
            if(rs.next()){
                count = rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.closeAll();
        }
        return count;
    }

    @Override
    public int insertBranches(Branches b) {
        String sql = "insert into branches(businessno,name,cityarea,address,telephone,summary) values(?,?,?,?,?,?)";
        int count = this.executeUpdate(sql,new Object[]{b.getBusinessno(),b.getName(),b.getCityarea(),b.getAddress(),b.getTelephone(),b.getSummary()});
        return count;
    }

    @Override
    public Branches getBranchesById(int id) {
        Branches b = null;
        String sql = "select * from branches where id = ?";
        rs = this.getResultSet(sql,new Object[]{id});
        try {
            if (rs.next()){
                b = new Branches();
                b.setId(rs.getInt("id"));
                b.setAddress(rs.getString("address"));
                b.setBusinessno(rs.getString("businessno"));
                b.setCityarea(rs.getString("cityarea"));
                b.setName(rs.getString("name"));
                b.setSummary(rs.getString("summary"));
                b.setTelephone(rs.getString("telephone"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.closeAll();
        }
        return b;
    }

    @Override
    public int deleteBranchesById(int id) {
        String sql = "delete from branches where id = ?";
        int flag = this.executeUpdate(sql,new Object[]{id});
        return flag;
    }
}
